package com.yixing.tech.wms.statistics.stream;

import com.yixing.tech.wms.statistics.service.IInventoryOperationFlowStatisticsService;
import com.yixing.tech.wms.stock.out.domain.StockOutOperation;
import com.mongodb.client.model.changestream.ChangeStreamDocument;
import com.mongodb.client.model.changestream.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.data.mongodb.core.messaging.Message;
import org.springframework.data.mongodb.core.messaging.MessageListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

@Component
@Slf4j
public class StockOutOperationListener implements MessageListener<ChangeStreamDocument<Document>, StockOutOperation>  {

    @Resource
    IInventoryOperationFlowStatisticsService inventoryOperationFlowStatisticsService;

    @Override
    public void onMessage(Message<ChangeStreamDocument<Document>, StockOutOperation> message) {
        OperationType operationType = message.getRaw().getOperationType();
        log.error("操作类型:{}", operationType);
        log.error("变更数据主体:{}", message.getBody());

        if(OperationType.UPDATE.equals(operationType)) {
            Object operationState = message.getBody().getOperationState();
            if(operationState == null) {
                message.getBody().setOperationState("");
            }else if(operationState instanceof Map) {
                String state = ((Map<String, Object>) operationState).get("id").toString();
                message.getBody().setOperationState(state);
            }
            inventoryOperationFlowStatisticsService.insertInventoryOperationFlowFromStockOutOperation(message.getBody());
        }
    }
}
